from fastapi import APIRouter
from fastapi.params import Depends
from pydantic import BaseModel, Field
from sqlalchemy import text
from sqlalchemy.orm import Session

from commons.BaseResponse import BaseResponse
from datebase import get_db
from utils.EncryptionUtil import EncryptionMiddleware, TokenVerify

data_app_system = APIRouter(prefix="/user", tags=["app系统管理"])


class UserForm(BaseModel):
    logUser: int = Field(..., description="用户id")
    passWord: str = Field(..., description="密码")


@data_app_system.post("/login", summary="app登录接口")
def dologin(user: UserForm, db: Session = Depends(get_db)):
    username = user.logUser
    password = user.passWord
    sql = "select password_clear,id,username,fsite_no_belong"
    sql = sql + " from am_sys_user"
    sql = sql + " where id= :username "
    data = db.execute(text(sql), {
        "username": username,
    }).fetchall()

    spassword = ""
    fsiteNo = ""
    fusername = ""
    fuserid = ""
    for key in range(len(data)):
        spassword = data[key][0]
        fuserid = data[key][1]
        fusername = data[key][2]
        fsiteNo = data[key][3]

    if (password == spassword):
        tokenVerify = TokenVerify(
            user_id=fuserid,
            user_name=fusername,
        )
        token = EncryptionMiddleware.encrypt_token(tokenVerify)
        strCode = str(token, 'utf-8')
        # print(strCode)

        data = {"createTime": None,
                "createId": None,
                "updateTime": None,
                "updateId": None,
                "id": None,
                "username": fusername,
                "password": None,
                "passwordClear": None,
                "icon": None,
                "email": None,
                "nickName": None,
                "note": None,
                "loginTime": None,
                "status": None,
                "phone": None,
                "fsiteNoBelong": None,
                "ftype": None,
                "fcard": None,
                "fpointNoes": None,
                "enterpriseWechat": None,
                "fpointNoesVo": None,
                "froleid": None,
                "roleIds": None,
                "fusername": fusername,
                "fsiteNo": fsiteNo,
                "fsiteName": None,
                "fsiteLevel": None,
                "excludeAdmin": 0,
                "fuserid": fuserid,
                "token": strCode,
                "ftaskno": None,
                "ftaskname": None,
                "fteamno": None
                }
        return BaseResponse.success(data=data)
    else:
        return BaseResponse.error(message="密码不正确")
